package com.controller;

import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch.indices.Alias;
import com.es.EsRestClientUtil;
import com.es.vo.EsRestIndexVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * xxx
 *
 * @author heyonghao
 * @date 2023/2/3
 */
@RestController
@RequestMapping("/esIndex")
public class EsIndexController {

    @Autowired
    private EsRestClientUtil esRestClientUtil;


    @GetMapping("/exist")
    public Boolean esclienAdd(String indexName) {
        return esRestClientUtil.existIndex(indexName);
    }

    @GetMapping("/countIndex")
    public Long countIndex(String indexName) {
        return esRestClientUtil.countIndex(indexName);
    }

    @GetMapping("/createIndex")
    public Boolean createIndex() {
        EsRestIndexVo esRestIndexVo = new EsRestIndexVo();
        esRestIndexVo.setName("goos_index");
        esRestIndexVo.setAliases("goods");
        esRestIndexVo.setAliasSetting(Alias.of(e->e.searchRouting("1,2")));
        Map<String, Property> property = new HashMap<>(16);
        property.put("goodsName",Property.of(p->p.text(e->e.analyzer("ik_max_word"))));
        property.put("price",Property.of(p->p.double_(e->e.nullValue(0d))));
        property.put("stock",Property.of(p->p.integer(e->e.nullValue(0))));
        property.put("desc",Property.of(p->p.text(e->e.analyzer("ik_max_word"))));
        property.put("tags",Property.of(p->p.keyword(e->e.nullValue(""))));
        property.put("inStockTime",Property.of(p->p.date(e->e.format("yyyy-MM-dd HH:mm:ss"))));
        esRestIndexVo.setProperty(property);
        return esRestClientUtil.createIndex(esRestIndexVo);
    }

    @GetMapping("/delIndex")
    public Boolean delIndex(String indexName){
        return esRestClientUtil.delIndex(indexName);
    }

    @GetMapping("/addIndexAliases")
    public Boolean aliasesIndex(String indexName,String aliases){
        return esRestClientUtil.addIndexAliases(indexName,aliases);
    }

    @GetMapping("/delIndexAliases")
    public Boolean delIndexAliases(String indexName,String aliases){
        return esRestClientUtil.delIndexAliases(indexName, Arrays.asList(aliases));
    }


}
